<template>
  <div class="main user-layout-register">
    <h3><span>微信扫码登录/注册</span></h3>
    <a-form-model ref="form" :model="model">
      <a-form-model-item prop="username">
        <div class="wxCodeBox" v-if="userResultData === null">
          <img :src="qr_url" class="img" alt=""  />
          <!-- <div class="img" v-viewer>
            <div class="dark" @click="btnRefresh" v-if="refreshModel">已超时，点击刷新</div>
            <div id="wx_login_container" class="img" style="height: 310px"></div>
          </div> -->
          <div class="img">
            <div class="loading" v-if="!loading"></div>
          </div>
          <div class="wxTitle">首次扫码后将自动注册新账号</div>
        </div>
        <div class="wxCodeBox" v-else>
          <img class="pho" src="../../../assets/account.jpg"/>
          <div class="h6">登录成功，正在进入首页...</div>
        </div>
      </a-form-model-item>

      <!-- <a-form-model-item prop="password2">
        <a-input v-model="model.password2" size="large" type="password" autocomplete="false" placeholder="确认密码"></a-input>
      </a-form-model-item> -->

      <a-form-model-item>
        <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script type="text/javascript" src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<script>
import { mapActions, mapGetters, mapState } from 'vuex'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_NAME,USER_INFO,USER_AUTH,SYS_BUTTON_AUTH,UI_CACHE_DB_DICT_DATA,TENANT_ID,CACHE_INCLUDED_ROUTES,LIMIT_LIST,DATA_MONITOR,ACCESS_CODE } from "@/store/mutation-types"
import { welcome } from "@/utils/util"
import { wxLogin } from '@/utils/wxLogin.js'
import { getFileAccessHttpUrl, getAction } from '@/api/manage'
import { mixinDevice } from '@/utils/mixin.js'
import { getSmsCaptcha } from '@/api/login'
import { checkOnlyUser } from '@/api/api'
const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强',
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success',
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a',
}
export default {
  name: 'ScanCode',
  components: {},
  mixins: [mixinDevice],
  data() {
    return {
      model: {},
      urltest: '',
      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000',
      },
      registerBtn: false,
      qr_url: '',
      loading: false,
      tem_poll: null,
      scene: '',
      userInfoData: {},
      userResultData:null,
      refreshModel:false,
    }
  },
  computed: {},
  mounted() {
    this.getQrUrl()
    // let code = JSON.parse(sessionStorage.getItem('RECOMMEND_CODE') || "[]");
    // console.log('RECOMMEND_CODE',code)
  },
  beforeDestroy() {
    //清除定时器
    this.getClearInterval()
  },
  methods: {
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    ...mapActions(['Login', 'userLimitList','weChatQr']),
    //点击刷新
    btnRefresh(){
      this.refreshModel = false
      this.loading = true
      this.getQrUrl()
    },
    getClearInterval(){
      clearInterval(this.tem_poll)
      this.tem_poll = null
    },
    getQrUrl() {
      this.loading = false
      var code;
      try{
        code = JSON.parse(sessionStorage.getItem('RECOMMEND_CODE') || "")
      }catch{
        code = ''
      }

      this.$http
        .post('/wechat/api/getLoginQrCode/?code=' + code)
        .then((res) => {
          this.qr_url = res.result
          var themObj = this.getRequest(this.qr_url)
          console.log('this.getRequest(this.qr_url)', this.getRequest(this.qr_url))
          // 第二种方法获取微信二维码
          let APPID = themObj.appid //网页应用微信开放平台appid
          let REDIRECT_URI = encodeURIComponent(themObj.redirect_uri) //这个是在微信开发工具网页端的地方填写的地址 - 授权回调域 中 后面可添加
          // this.urltest = `https://open.weixin.qq.com/connect/qrconnect?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect`
          // var obj = new WxLogin({
          //   self_redirect: true,
          //   id: 'wx_login_container',
          //   appid: 'wx7601ccd1732edde1',
          //   scope: 'snsapi_login',
          //   redirect_uri: REDIRECT_URI,
          //   state: themObj.state,
          //   style: 'black',
          //   href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIxMHB4O21hcmdpbi10b3A6MjVweDtib3JkZXI6MH0KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge3dpZHRoOiAyNDBweDtjb2xvcjogd2hpdGU7fQouc3RhdHVzX2ljb24ge2Rpc3BsYXk6bm9uZX0KLmltcG93ZXJCb3ggLnN0YXR1cyB7dGV4dC1hbGlnbjogY2VudGVyO3BhZGRpbmc6MH0K',
          // })
          this.loading = true
          this.scene = res.message
          this.tem_poll = setInterval(this.loginPoll, 1000)
          setTimeout(() => {
            this.getClearInterval()
            this.refreshModel = true
          }, 60000);
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    getRequest(url) {
      var url = url //获取url中"?"符后的字串
      var theRequest = new Object()
      if (url.indexOf('?') != -1) {
        var str = url.substr(1)
        var strOther = str.split('&')
        for (var i = 0; i < strOther.length; i++) {
          theRequest[strOther[i].split('=')[0]] = decodeURI(strOther[i].split('=')[1])
        }
      }
      return theRequest
    },

    loginPoll() {
      this.$http
        .post('/wechat/api/wechatOpenIdLogin?sceneStr=' + this.scene)
        .then((res) => {
            this.userResultData = res.result
            console.log('this.userResultData',this.userResultData)
          if (res.success) {
            Vue.ls.set(ACCESS_CODE, res.result.code, 30 * 24 * 60 * 60 * 1000)
            this.userInfoData = res.result.userInfo
            // 清除定时器
            this.getClearInterval()
            setTimeout(() => {
              this.wxLogin(res.result)
            }, 3000);

            return
          }
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    //账号密码登录
    wxLogin(results) {
      localStorage.setItem('username', JSON.stringify(this.userInfoData.username))
      localStorage.setItem('userAll', JSON.stringify(this.userInfoData))
      const result = results
      const userInfo = result.userInfo
      Vue.ls.set(ACCESS_TOKEN, result.token, 30 * 24 * 60 * 60 * 1000)
      Vue.ls.set(USER_NAME, userInfo.username, 30 * 24 * 60 * 60 * 1000)
      Vue.ls.set(USER_INFO, userInfo, 30 * 24 * 60 * 60 * 1000)
      Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 30 * 24 * 60 * 60 * 1000)
      this.$store.commit('SET_TOKEN', result.token)
      this.$store.commit('SET_INFO', userInfo)
      this.$store.commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
      this.$store.commit('SET_AVATAR', userInfo.avatar)
      this.loginSuccess()
      this.$store.dispatch('userLimitList', { userId: this.userInfo().id })
    },
    //登录成功
    loginSuccess() {
      this.$router.push({ path: '/dashboard/analysis' }).catch(() => {
        console.log('登录跳转首页出错,这个错误从哪里来的')
      })
      this.$notification.success({
        message: '欢迎',
        description: `开始你的创作趴`,
      })
    },
    getAvatar() {
      console.log('this.avatar()',this.avatar())
      return getFileAccessHttpUrl(this.avatar())
    },
  },
  watch: {
    //监听路由地址的改变
    $route: {
      immediate: true,
      handler() {
        console.log('this.newMessage', this.$route.query.param)
      },
    },
  },
}
</script>
<style lang="less">
.user-register {
  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #52c41a;
  }
}

.user-layout-register {
  .ant-input-group-addon:first-child {
    background-color: #fff;
  }
}
</style>
<style lang="less" scoped>
.user-layout-register {
  & > h3 {
    font-size: 16px;
    margin-bottom: 30px;
    display: inline-block;
    width: 100%;
    text-align: center;
    span {
      color: #1890ff;
      padding: 12px 16px;
      border-bottom: 2px solid #1890ff;
    }
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .register-button {
    width: 50%;
    background: linear-gradient(90deg, #7a6cfc, #f26dbe);
    border: unset;
  }

  .login {
    float: right;
    line-height: 40px;
  }
}

.wxCodeBox {
  text-align: center;
  padding: 10px;
  img{
    width: 60%;
  }
  .pho{
    width: 100px;
    border-radius: 50%;
    padding: 5px;
    background: linear-gradient(49deg, #402fe4, #f26df2);
  }
  .h6{
    font-size: 16px;
    color: white;
    letter-spacing: 2px;

  }
  .img {
    display: flex;
    margin: auto;
    justify-content: center;
    // background: white;
    border-radius: 8px;
    // background-color: rgba(255, 255, 255, 0.7);
    overflow: hidden;
    position: relative;
    .dark{
      position: absolute;
      top: 25px;
      z-index: 9;
      background-color: rgba(0, 0, 0, 0.7);
      width: 211px;
      height: 211px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }
  .wxTitle {
    color: white;
  }
}

.loading {
  width: 30px;
  height: 30px;
  border: 2px solid #1890ff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: rotate-data-v-791e0f36 0.75s linear infinite;
  float: right;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

/deep/#wx_login_container {
  .impowerBox .qrcode {width: 210px;margin-top:25px;border:0}
  .impowerBox .title {display: none;}
  .impowerBox .info {width: 240px;color: white;}
  .status_icon {display:none}
  .impowerBox .status {text-align: center;padding:0}
  }
</style>